﻿using System.Collections;

namespace SDL
{
    public abstract class DbSettings
    {
        private Hashtable _Loaded;

        protected DbSettings()
        {
            Load();
        }

        public abstract void Load();

        public abstract void Save(string Key, object Value);

        public void Load(Hashtable data)
        {
            _Loaded = data;
            var Members = GetType().GetMembers();
            foreach (var Member in Members)
            {
                var attrs = Member.GetCustomAttributes(typeof(DbSettingAttribute), false);
                foreach (DbSettingAttribute attr in attrs)
                {
                    if (_Loaded.ContainsKey(attr.FieldName))
                    {
                        this.SetField(Member.Name, new[] { _Loaded[attr.FieldName] });
                    }
                }
            }
        }

        public void Save()
        {
            var settings = getSettings();
            var differences = settings.GetDifferences(_Loaded);
            foreach (var key in differences.Keys)
            {
                Save(key.ToString(), differences[key]);
            }
        }

        public Hashtable getSettings()
        {
            var result = new Hashtable();
            var Members = GetType().GetMembers();
            foreach (var Member in Members)
            {
                var attrs = Member.GetCustomAttributes(typeof(DbSettingAttribute), false);
                foreach (DbSettingAttribute attr in attrs)
                {
                    result.Add(attr.FieldName, this.GetField(Member.Name));
                }
            }
            return (result);
        }
    }
}
